package com.base.leetcode;

/**
 * @Author: hdhao
 * @Create: 2023/3/30 - 20:01
 * @Version: v1.0
 */
//有序链表去重(重复的元素一个不留)
public class Leetcode82 {

    //方法1
    public static ListNode deleteDuplicates1(ListNode p){
        if (p == null || p.next == null){
            return p;
        }
        if (p.val == p.next.val){
            ListNode x = p.next.next;
            while (x!=null && x.val == p.val){
                x = x.next;
            }
            //这里的x就是与p取值不同的节点
            return deleteDuplicates1(x);
        }else {
            return p;
        }
    }

    //方法2
    public static ListNode deleteDuplicates2(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        //哨兵节点
        ListNode sentinel = new ListNode(-1, head);
        ListNode p1 = sentinel;
        ListNode p2;
        ListNode p3;
        while ((p2 = p1.next)!=null
                    && (p3=p2.next)!=null){
            if (p2.val == p3.val){
                while ((p3=p3.next)!=null && p3.val == p2.val){

                }
                //此时的p3找到了不重复的值
                p1.next = p3;
            }else {
                p1 = p1.next;
            }
        }
        return sentinel.next;
    }
}
